import userStorage from "../../utils/userStorage";

const state = {
  // 私聊消息存储 { playerId: [messages] }
  privateMessages: {},
  
  // 未读消息计数 { playerId: count }
  unreadCounts: {},
  
  // 连接状态
  isConnected: false,
  
  // 最后活跃时间
  lastActiveTime: Date.now()
};

const getters = {
  // 获取指定玩家的消息
  getPlayerMessages: (state) => (playerId) => {
    return state.privateMessages[playerId] || [];
  },
  
  // 获取指定玩家的未读数量
  getUnreadCount: (state) => (playerId) => {
    return state.unreadCounts[playerId] || 0;
  },
  
  // 获取总未读数量
  getTotalUnreadCount: (state) => {
    return Object.values(state.unreadCounts).reduce((total, count) => total + count, 0);
  },
  
  // 检查是否有未读消息
  hasUnreadMessages: (state) => {
    return Object.values(state.unreadCounts).some(count => count > 0);
  }
};

const mutations = {
  // 添加消息
  addMessage(state, { playerId, message }) {

    
    if (!state.privateMessages[playerId]) {
      state.privateMessages[playerId] = [];

    }
    
    // 检查消息是否已存在（防重复）
    const exists = state.privateMessages[playerId].some(msg => msg.id === message.id);
    if (!exists) {
      state.privateMessages[playerId].push({
        ...message,
        timestamp: message.timestamp || Date.now()
      });
      
      // 按时间排序
      state.privateMessages[playerId].sort((a, b) => a.timestamp - b.timestamp);
      
      // 保持最多200条消息
      if (state.privateMessages[playerId].length > 200) {
        state.privateMessages[playerId] = state.privateMessages[playerId].slice(-200);
      }
      
      // 强制触发Vue响应式更新
      state.privateMessages = { ...state.privateMessages };
      
      // 持久化存储
      saveMessagesToStorage(state);
      
    }
  },
  
  // 标记消息为已读
  markAsRead(state, { playerId, messageId }) {
    const messages = state.privateMessages[playerId];
    if (messages) {
      const message = messages.find(msg => msg.id === messageId);
      if (message) {
        message.isRead = true;
        saveMessagesToStorage(state);
      }
    }
  },
  
  // 增加未读计数
  incrementUnread(state, playerId) {
    if (!state.unreadCounts[playerId]) {
      state.unreadCounts[playerId] = 0;
    }
    state.unreadCounts[playerId]++;
    saveUnreadCountsToStorage(state);
  },
  
  // 清除未读计数
  clearUnread(state, playerId) {
    if (state.unreadCounts[playerId]) {
      state.unreadCounts[playerId] = 0;
      saveUnreadCountsToStorage(state);
    }
  },
  
  // 设置连接状态
  setConnectionStatus(state, isConnected) {
    state.isConnected = isConnected;
  },
  
  // 更新最后活跃时间
  updateLastActiveTime(state) {
    state.lastActiveTime = Date.now();
  },
  
  // 初始化聊天数据
  initializeChatData(state) {
    // 从本地存储加载数据
    const savedMessages = loadMessagesFromStorage();
    const savedUnreadCounts = loadUnreadCountsFromStorage();
    
    if (savedMessages) {
      state.privateMessages = savedMessages;
    }
    
    if (savedUnreadCounts) {
      state.unreadCounts = savedUnreadCounts;
    }
  },
  
  // 清除聊天数据
  clearChatData(state) {
    state.privateMessages = {};
    state.unreadCounts = {};
    clearStorageData();
  },
  
  // 删除指定玩家的聊天记录
  clearPlayerMessages(state, playerId) {
    if (state.privateMessages[playerId]) {
      delete state.privateMessages[playerId];
    }
    if (state.unreadCounts[playerId]) {
      delete state.unreadCounts[playerId];
    }
    saveMessagesToStorage(state);
    saveUnreadCountsToStorage(state);
  }
};

const actions = {
  // 发送私聊消息
  async sendPrivateMessage({ commit, rootState }, { playerId, content }) {
    try {
      const message = {
        id: 'msg_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
        content: content.trim(),
        senderId: 'storyteller',
        receiverId: playerId,
        timestamp: Date.now(),
        isStoryteller: true,
        isRead: true,
        chatType: 'private'
      };
      
      // 添加到本地存储
      commit('addMessage', { playerId, message });
      
      // 通过Socket发送
      if (rootState.socket && rootState.socket.connected) {
        rootState.socket.emit('private_message', {
          roomId: rootState.session.sessionId,
          ...message
        });
      }
      
      return message;
    } catch (error) {
      console.error('发送私聊消息失败:', error);
      throw error;
    }
  },
  
  // 接收私聊消息
  receivePrivateMessage({ commit }, { senderId, message }) {

    
    // 添加消息
    commit('addMessage', { 
      playerId: senderId, 
      message: {
        ...message,
        isRead: false
      }
    });
    
    // 增加未读计数
    commit('incrementUnread', senderId);
    
    // 更新活跃时间
    commit('updateLastActiveTime');
  },
  
  // 标记玩家消息为已读
  markPlayerMessagesAsRead({ commit, state }, playerId) {
    const messages = state.privateMessages[playerId];
    if (messages) {
      messages.forEach(message => {
        if (!message.isRead && !message.isStoryteller) {
          commit('markAsRead', { playerId, messageId: message.id });
        }
      });
    }
    commit('clearUnread', playerId);
  },
  
  // 初始化聊天模块
  initializeChat({ commit }) {
    commit('initializeChatData');
    commit('updateLastActiveTime');
  },
  
  // 清理过期数据
  cleanupOldMessages({ state }) {
    const now = Date.now();
    const sevenDaysAgo = now - (7 * 24 * 60 * 60 * 1000); // 7天前
    
    let hasChanges = false;
    
    Object.keys(state.privateMessages).forEach(playerId => {
      const messages = state.privateMessages[playerId];
      const filteredMessages = messages.filter(msg => msg.timestamp > sevenDaysAgo);
      
      if (filteredMessages.length !== messages.length) {
        state.privateMessages[playerId] = filteredMessages;
        hasChanges = true;
      }
      
      // 如果该玩家没有消息了，删除整个键
      if (filteredMessages.length === 0) {
        delete state.privateMessages[playerId];
        if (state.unreadCounts[playerId]) {
          delete state.unreadCounts[playerId];
        }
      }
    });
    
    if (hasChanges) {
      saveMessagesToStorage(state);
      saveUnreadCountsToStorage(state);
    }
  }
};

// 本地存储辅助函数
const STORAGE_KEYS = {
  CHAT_MESSAGES: 'bt_chat_messages',
  CHAT_UNREAD: 'bt_chat_unread',
  CHAT_LAST_CLEANUP: 'bt_chat_last_cleanup'
};

function saveMessagesToStorage(state) {
  try {
    userStorage.setItem(STORAGE_KEYS.CHAT_MESSAGES, state.privateMessages);
  } catch (error) {
    console.error('保存聊天消息失败:', error);
  }
}

function saveUnreadCountsToStorage(state) {
  try {
    userStorage.setItem(STORAGE_KEYS.CHAT_UNREAD, state.unreadCounts);
  } catch (error) {
    console.error('保存未读计数失败:', error);
  }
}

function loadMessagesFromStorage() {
  try {
    return userStorage.getItem(STORAGE_KEYS.CHAT_MESSAGES) || {};
  } catch (error) {
    console.error('加载聊天消息失败:', error);
    return {};
  }
}

function loadUnreadCountsFromStorage() {
  try {
    return userStorage.getItem(STORAGE_KEYS.CHAT_UNREAD) || {};
  } catch (error) {
    console.error('加载未读计数失败:', error);
    return {};
  }
}

function clearStorageData() {
  try {
    userStorage.removeItem(STORAGE_KEYS.CHAT_MESSAGES);
    userStorage.removeItem(STORAGE_KEYS.CHAT_UNREAD);
  } catch (error) {
    console.error('清除聊天存储失败:', error);
  }
}

// 检查是否需要清理旧数据
function shouldCleanupOldMessages() {
  try {
    const lastCleanup = userStorage.getItem(STORAGE_KEYS.CHAT_LAST_CLEANUP);
    const now = Date.now();
    const oneDayAgo = now - (24 * 60 * 60 * 1000); // 1天前
    
    return !lastCleanup || lastCleanup < oneDayAgo;
  } catch (error) {
    return true; // 发生错误时进行清理
  }
}

function markCleanupCompleted() {
  try {
    userStorage.setItem(STORAGE_KEYS.CHAT_LAST_CLEANUP, Date.now());
  } catch (error) {
    console.error('标记清理完成失败:', error);
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};

// 导出清理函数供外部使用
export { shouldCleanupOldMessages, markCleanupCompleted };